<template>
  <div class="app-container bg">
    <div class="box-container">
      <div
        class="mb15"
        style="border-bottom: 1px solid #ddd; margin-bottom: 10px"
      >
        <el-radio-group v-model="showType" @change="showTypeChange">
          <el-radio-button label="1">科室</el-radio-button>
          <el-radio-button label="2">学员</el-radio-button>
        </el-radio-group>
      </div>

      <el-row
        :gutter="10"
        class="mb15 flex-container"
        style="
          font-size: 14px;
          line-height: 25px;
          margin-top: 20px;
          cursor: pointer;
          border-bottom: 1px solid #ddd;
        "
      >
        <el-col :span="3.5">
          <div
            @click="clickAll(0, null)"
            class="nactive"
            :class="{ active: tagIndex == 0 }"
          >
            全部：{{ registerBaseVo.total || 0 }}
          </div>
        </el-col>
        <el-col :span="3.5">
          <div
            @click="clickAll(1, 1)"
            class="nactive"
            :class="{ active: tagIndex == 1 }"
          >
            未开始：{{ registerBaseVo.cultureStatus1 || 0 }}
          </div>
        </el-col>
        <el-col :span="3.5">
          <div
            @click="clickAll(2, 2)"
            class="nactive"
            :class="{ active: tagIndex == 2 }"
          >
            进修中：{{ registerBaseVo.cultureStatus2 || 0 }}
          </div>
        </el-col>
        <el-col :span="3.5">
          <div
            @click="clickAll(3, 3)"
            class="nactive"
            :class="{ active: tagIndex == 3 }"
          >
            已结业：{{ registerBaseVo.cultureStatus3 || 0 }}
          </div>
        </el-col>
        <el-col :span="3.5">
          <div
            @click="clickAll(4, 4)"
            class="nactive"
            :class="{ active: tagIndex == 4 }"
          >
            进修终止：{{ registerBaseVo.cultureStatus4 || 0 }}
          </div>
        </el-col>
      </el-row>

      <el-row v-if="showType == 2" :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            :disabled="multiple"
            @click="modifyOpen"
            >变更进修</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="evaluateOpen"
            >设置考评时间</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            @click="scoreOpen"
            v-has-role="['teacher']"
            >导入考评分数</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            @click="levelOpen"
            v-has-role="['secretary']"
            >导入考评等级</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-dropdown @command="handleExportCommand">
            <el-button type="primary" size="mini">
              导出学员<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="exportStudent"
                >导出学员</el-dropdown-item
              >
              <el-dropdown-item command="exportStudentSummary"
                >导出学员汇总</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            :disabled="multiple"
            @click="manualOpen"
            >导出学员手册</el-button
          >
        </el-col>
      </el-row>
    </div>
    <el-form
      class="box-container"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="" style="width: 160px" prop="registerDeptId">
        <el-select
          v-model="queryParams.registerDeptId"
          placeholder="请选择进修科目"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerDeptList"
            :key="index"
            :label="item.registerDeptName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label=""
        style="width: 160px"
        prop="registerTypeId"
        v-if="false"
      >
        <el-select
          v-model="queryParams.registerTypeId"
          placeholder="请选择招生类型"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerTypeList"
            :key="index"
            :label="item.registerTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="batchName">
        <el-select
          v-model="queryParams.batchName"
          placeholder="请选择招生批次"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerBatchList"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="registerYear">
        <el-date-picker
          v-model="queryParams.registerYear"
          type="year"
          placeholder="请选择招生年份"
          format="yyyy"
          style="width: 160px"
          value-format="yyyy"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 结束时间筛选 -->
      <el-form-item label="" style="width: 160px" prop="searchRangeEndDate">
        <el-date-picker
          v-model="queryParams.searchRangeEndDate"
          type="date"
          value-format="yyyy/MM"
          format="yyyy/MM"
          placeholder="请选择结业日期"
          style="width: 160px"
          @change="handleQuery"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="box-container">
      <div v-if="showType == 1" class="custom-table">
        <div class="custom-dept" v-for="(row, index) in dataList" :key="index">
          <div class="colw title">{{ row.registerDeptName }}</div>
          <div class="colw flex">
            <div class="col">
              {{ row.total }}
              <div class="desc">录取总数</div>
            </div>

            <div class="col">
              <span class="red">{{ row.cultureStatus1 }}</span>
              <div class="desc">未开始</div>
            </div>
            <div class="col">
              {{ row.cultureStatus2 }}
              <div class="desc">进修中</div>
            </div>
            <div class="col">
              {{ row.cultureStatus3 }}
              <div class="desc">已结业</div>
            </div>
          </div>
          <div class="colw func" @click="viewOpen(row)">
            <el-button size="small" type="primary">查看名单</el-button>
          </div>
        </div>
      </div>
      <div v-if="showType == 2" class="custom-table">
        <el-checkbox
          v-model="AllCheck"
          @change="handleSelectionChangeAll"
          style="transform: scale(1.2); margin-bottom: 20px; margin-left: 20px"
          >全选</el-checkbox
        >
        <div
          class="custom-register"
          v-for="(row, index) in dataList"
          :key="row.id"
        >
          <div class="border" style="display: flex; flex: 8">
            <div>
              <div class="user-name">
                <div style="margin-right: 10px">
                  <el-checkbox
                    v-model="row.check"
                    style="transform: scale(1.2)"
                    @change="handleSelectionChange($event, index)"
                  />
                </div>
                <span
                  style="
                    font-size: 18px;
                    font-weight: bolder;
                    color: #a52529;
                    cursor: pointer;
                  "
                  @click="detailOpenInfo(row)"
                  >{{ row.userName }}</span
                >
                <el-tag
                  type="success"
                  v-if="row.graduationStatus == 1"
                  size="small"
                  style="margin-left: 10px"
                  >正常结业</el-tag
                >
                <el-tag
                  v-if="row.graduationStatus == 2"
                  size="small"
                  style="
                    margin-left: 10px;
                    background-color: #f6eee0;
                    color: #e2a440;
                  "
                  >提前结业</el-tag
                >
                <el-tag
                  type="warning"
                  v-if="row.graduationStatus == 3"
                  size="small"
                  style="margin-left: 10px"
                  >终止进修</el-tag
                >
                <el-tag
                  type="danger"
                  v-if="row.graduationStatus == 4"
                  size="small"
                  style="margin-left: 10px"
                  >延期结业</el-tag
                >
                <el-tag
                  type="success"
                  v-if="!row.graduationStatus"
                  size="small"
                  style="margin-left: 10px"
                  >进修中</el-tag
                >

                <div style="margin-left: auto; font-size: 12px; color: #999">
                  工号：{{ row.jobNumber }}
                </div>
              </div>
              <div class="info">
                <div class="flexInfo">
                  <div>进修科目：{{ row.registerDeptName }}</div>
                  <div style="display: flex">
                    进修期限：
                    <span v-if="row.registerNoticeVo"
                      >{{ row.registerNoticeVo.startDate }} -
                      {{ row.registerNoticeVo.endDate }}</span
                    >
                    <div v-if="row.durationName">
                      （{{ row.durationName }}）
                    </div>
                  </div>
                  <div style="display: flex; align-items: center">
                    带教老师：
                    <div
                      v-for="(item, index) in row.registerAllocationVoList"
                      :key="index"
                    >
                      {{ item.teacherNickName }}
                      <el-tag
                        effect="dark"
                        size="small"
                        type="warning"
                        v-if="item.scoreStatus == 1"
                        >未评分</el-tag
                      >
                      <el-tag
                        effect="dark"
                        size="small"
                        type="success"
                        v-if="item.scoreStatus == 2"
                        >已评分</el-tag
                      >
                    </div>
                  </div>
                </div>
                <div class="flexInfo">
                  <template
                    v-if="
                      row.registerAllocationVoList &&
                      row.registerAllocationVoList.length > 1
                    "
                  >
                    <el-tooltip placement="top-start">
                      <div slot="content">
                        <div>考核综合得分:{{ row.scoreTotal }}</div>

                        <div
                          v-for="(item, index) in row.registerAllocationVoList"
                          :key="index"
                        >
                          {{ item.teacherNickName }}: {{ item.scoreTotal }}
                        </div>
                      </div>
                      <div style="display: inline-block">
                        考评分数：{{ row.scoreTotal }}
                      </div>
                    </el-tooltip>
                  </template>

                  <div>申请单位：{{ row.unitHospitalName }}</div>
                  <div>
                    考评等级：{{ row.scoreLevel }}
                    <el-tag
                      effect="dark"
                      size="small"
                      type="success"
                      v-if="row.scoreLevel"
                      >已评级</el-tag
                    >
                    <el-tag effect="dark" size="small" type="warning" v-else
                      >未评级</el-tag
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col border" v-if="isTeacher">
            <i class="el-icon-edit systemColor" style="font-size: 20px"></i>
            <!-- 审批历史按钮 -->
            <el-button size="mini" type="text" @click="scoreRowOpen(row)">
              考评评分
            </el-button>
          </div>
          <div class="col border" v-if="isSecretary">
            <i class="el-icon-edit systemColor" style="font-size: 20px"></i>
            <!-- 审批历史按钮 -->
            <el-button size="mini" type="text" @click="levelRowOpen(row)">
              考评评级
            </el-button>
          </div>
          <div class="col border">
            <i class="el-icon-edit systemColor" style="font-size: 20px"></i>
            <!-- 审批历史按钮 -->
            <el-button size="mini" type="text" @click="detailOpen(row)">
              记录手册
            </el-button>
            <el-button size="mini" type="text" @click="previewOpen(row)">
              预览记录手册
            </el-button>
          </div>
        </div>
      </div>
      <el-dialog
        title="记录手册"
        :visible.sync="previewShow"
        width="1000px"
        append-to-body
        :close-on-click-modal="false"
      >
        <iframe
          v-if="previewShow"
          :src="pdfUrl"
          width="100%"
          height="600"
          frameborder="0"
          type="application/pdf"
        ></iframe>
      </el-dialog>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog
      title="报名详情"
      :visible.sync="detailShowInfo"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerInfoDetailInfo
        v-if="detailShowInfo"
        :register-id="registerInfo.id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailShowInfo = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="变更进修"
      :visible.sync="modifyShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="modifyForm"
        :model="modifyForm"
        :rules="modifyRules"
        label-width="80px"
      >
        <el-form-item label="结业状态" prop="graduationStatus">
          <el-radio-group v-model="modifyForm.graduationStatus">
            <el-radio
              v-for="(item, index) in graduationStatusList"
              :key="index"
              :label="item.id"
              >{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="结业日期" prop="endDate">
          <el-date-picker
            v-model="modifyForm.endDate"
            type="date"
            value-format="yyyy/MM/dd"
            format="yyyy/MM/dd"
            placeholder="请选择日期时间"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="进修备注" prop="engageRemark">
          <el-input
            type="textarea"
            :rows="5"
            v-model="modifyForm.engageRemark"
            placeholder="请输入进修备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="modifySubmit">确 定</el-button>
        <el-button @click="modifyShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="设置考评时间"
      :visible.sync="evaluateShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        class="evaluate"
        ref="evaluateForm"
        :model="evaluateForm"
        :rules="evaluateRules"
        label-width="140px"
      >
        <el-form-item label="学员开始考评时间" prop="examineType">
          <el-radio-group v-model="evaluateForm.examineType">
            <el-radio :label="1">带教开始时间</el-radio>
            <el-radio :label="2"
              >带教结束前
              <el-input
                type="number"
                v-model="evaluateForm.examineEndDay"
                style="width: 100px; margin-left: 5px; margin-right: 5px"
              />
              天内
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="evaluateSubmit">确 定</el-button>
        <el-button @click="evaluateShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="导入考评分数"
      :visible.sync="scoreShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div style="text-align: center">
        <el-divider content-position="left"
          >1、导出培养考核-考评分数</el-divider
        >
        <el-button type="primary" size="mini" @click="scoreExport"
          >导出列表</el-button
        >
        <el-divider content-position="left">2、导入考评打分后的文件</el-divider>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="scoreShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="导入考评等级"
      :visible.sync="levelShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div style="text-align: center">
        <el-divider content-position="left"
          >1、导出培养考核-考评等级</el-divider
        >
        <el-button type="primary" size="mini" @click="levelExport"
          >导出列表</el-button
        >
        <el-divider content-position="left">2、导入考评评级后的文件</el-divider>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="levelShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="考评评分"
      :visible.sync="scoreRowShow"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        class="score-row"
        ref="scoreRowForm"
        :model="scoreRowForm"
        :rules="scoreRowRules"
        label-width="0"
      >
        <div class="section">
          指标评分（评分人：{{ scoreRowForm.teacherNickName }}）
        </div>
        <div class="score-row-item">
          <div class="left">
            <div class="title">职业道德 (15分)</div>
            <div class="desc">遵守医德规范、廉洁自律、合理医疗、尊重患者</div>
          </div>
          <div class="right">
            <el-form-item label="" prop="scoreProfessional">
              <el-input
                type="number"
                v-model.number="scoreRowForm.scoreProfessional"
                oninput="if(value > 15) value = 15"
                style="width: 100px"
              />
            </el-form-item>
          </div>
        </div>
        <div class="score-row-item">
          <div class="left">
            <div class="title">劳动纪律 (20分)</div>
            <div class="desc">准时上下班，服从科室安排，坚守工作岗位</div>
          </div>
          <div class="right">
            <el-form-item label="" prop="scoreLabour">
              <el-input
                type="number"
                v-model.number="scoreRowForm.scoreLabour"
                oninput="if(value > 20) value = 20"
                style="width: 100px"
              />
            </el-form-item>
          </div>
        </div>
        <div class="score-row-item">
          <div class="left">
            <div class="title">工作责任性 (15分)</div>
            <div class="desc">
              积极参加科室业务学习、无医疗责任事故及严重差错
            </div>
          </div>
          <div class="right">
            <el-form-item label="" prop="scoreDuty">
              <el-input
                type="number"
                v-model.number="scoreRowForm.scoreDuty"
                oninput="if(value > 15) value = 15"
                style="width: 100px"
              />
            </el-form-item>
          </div>
        </div>
        <div class="score-row-item">
          <div class="left">
            <div class="title">操作能力 (30分)</div>
            <div class="desc">完成科室规定的临床工作量及要求掌握的诊疗技能</div>
          </div>
          <div class="right">
            <el-form-item label="" prop="scoreOperate">
              <el-input
                type="number"
                v-model.number="scoreRowForm.scoreOperate"
                oninput="if(value > 30) value = 30"
                style="width: 100px"
              />
            </el-form-item>
          </div>
        </div>
        <div class="score-row-item">
          <div class="left">
            <div class="title">病史报告书写 (20分)</div>
            <div class="desc">
              能按照要求规范书写病史、辅助科室检查记录、报告等
            </div>
          </div>
          <div class="right">
            <el-form-item label="" prop="scoreMedicalHistory">
              <el-input
                type="number"
                v-model.number="scoreRowForm.scoreMedicalHistory"
                oninput="if(value > 20) value = 20"
                style="width: 100px"
              />
            </el-form-item>
          </div>
        </div>
        <el-form-item label="" prop="scoreTotal">
          <div class="score-row-item">
            <div class="left">
              <div class="title" style="font-size: 18px; font-weight: bolder">
                综合评分
              </div>
            </div>
            <div
              class="right"
              style="font-size: 22px; font-weight: bolder; padding-right: 40px"
            >
              {{
                (scoreRowForm.scoreProfessional || 0) +
                (scoreRowForm.scoreLabour || 0) +
                (scoreRowForm.scoreDuty || 0) +
                (scoreRowForm.scoreOperate || 0) +
                (scoreRowForm.scoreMedicalHistory || 0)
              }}
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="scoreRowSubmit">确 定</el-button>
        <el-button @click="scoreRowShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="考评评级"
      :visible.sync="levelRowShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="levelRowForm"
        :model="levelRowForm"
        :rules="levelRowRules"
        label-width="100"
      >
        <el-form-item label="考评评级" prop="scoreLevel">
          <el-radio-group v-model="levelRowForm.scoreLevel">
            <el-radio label="优">优</el-radio>
            <el-radio label="良">良</el-radio>
            <el-radio label="合格">合格</el-radio>
            <el-radio label="不合格">不合格</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="levelRowSubmit">确 定</el-button>
        <el-button @click="levelRowShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="记录手册"
      :visible.sync="detailShow"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
      @close="detailShow = false"
    >
      <registerManual
        v-if="detailShow"
        :onlyread="true"
        :register-id="registerId"
        @close="detailShow = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import {
  queryByCountRegisterBase,
  queryByDeptRegisterBase,
  saveModifyRegisterBase,
  saveScoreRowRegisterBase,
} from "@/api/business/registerBase";

import { setupBatchData } from "@/utils/batchUtils";

import { listAllRegisterDept } from "@/api/business/registerDept";
import {
  delRegisterInfo,
  listRegisterInfo,
  updateRegisterInfo,
} from "@/api/business/registerInfo";
import { listAllRegisterType } from "@/api/business/registerType";
import { getSureInfo, updateSureInfo } from "@/api/business/sureInfo";
import { getToken } from "@/utils/auth";
import registerManual from "@/views/business/registerBase/audit/components/registerManual.vue";
import registerInfoDetailInfo from "../audit/components/registerInfoDetailInfo";

export default {
  name: "culture",
  components: { registerManual, registerInfoDetailInfo },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 招生信息表格数据
      dataList: [],
      //全选
      AllCheck: false,
      isTeacher: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 报到状态已报到
        sureStatus: 2,
        payNoRefund: 1,
        cultureStatus: null,
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
        searchRangeEndDate: null,
      },
      registerDeptList: [],
      registerTypeList: [],
      registerBatchList: consts.registerBatchList,
      registerBaseVo: {},
      batchDateList: [],

      // 页面显示
      showType: 1,
      // 变更进修
      graduationStatusList: consts.graduationStatusList,
      modifyShow: false,
      modifyForm: {},
      modifyRules: {
        graduationStatus: [
          { required: true, message: "结业状态不能为空", trigger: "blur" },
        ],
        endDate: [
          { required: true, message: "结业日期不能为空", trigger: "blur" },
        ],
        engageRemark: [
          { required: true, message: "进修备注不能为空", trigger: "blur" },
        ],
      },
      // 设置考评时间
      evaluateShow: false,
      evaluateForm: {},
      evaluateRules: {
        examineType: [
          {
            required: true,
            message: "请选择学员开始考评时间",
            trigger: "blur",
          },
        ],
      },
      registerInfo: {
        id: null,
      },
      detailShowInfo: false,
      // 导入考评分数
      scoreShow: false,
      // 导入考评等级
      levelShow: false,
      upload: {
        isUploading: false,
        headers: { Authorization: "Bearer " + getToken() },
        url: null,
      },
      // 考评评分
      scoreRowShow: false,
      scoreRowForm: {},
      scoreRowRules: {
        scoreProfessional: [
          { required: true, message: "职业道德打分不能为空", trigger: "blur" },
        ],
        scoreLabour: [
          { required: true, message: "劳动纪律打分不能为空", trigger: "blur" },
        ],
        scoreDuty: [
          {
            required: true,
            message: "工作责任性打分不能为空",
            trigger: "blur",
          },
        ],
        scoreOperate: [
          { required: true, message: "操作能力不能打分为空", trigger: "blur" },
        ],
        scoreMedicalHistory: [
          {
            required: true,
            message: "病史报告书写打分不能为空",
            trigger: "blur",
          },
        ],
      },
      // 考评评级
      levelRowShow: false,
      levelRowForm: {},
      levelRowRules: {
        scoreLevel: [
          { required: true, message: "考评评级不能为空", trigger: "blur" },
        ],
      },
      tagIndex: 0,
      // 记录手册
      registerId: null,
      detailShow: false,
      pdfUrl: null,
      // 预览记录手册
      previewShow: false,
      isSecretary: false,
    };
  },
  async created() {
    await this.getbatch();

    this.initData();
    this.listAllRegisterDept();
    this.listAllRegisterType();
    this.isSecretary = this.$store.getters.roles.indexOf("secretary") > -1;
    this.isTeacher = this.$store.getters.roles.indexOf("teacher") > -1;
  },
  computed: {
    pickerOptions() {
      if (this.modifyForm.graduationStatus != 2 || this.ids.length !== 1) {
        return {
          disabledDate: () => {
            return false;
          },
        };
      }
      const student = this.dataList.find((item) => item.id === this.ids[0]);
      if (!student || !student.registerNoticeVo) {
        return {
          disabledDate: () => {
            return false;
          },
        };
      }
      const startDate = new Date(student.registerNoticeVo.startDate);
      const endDate = new Date(student.registerNoticeVo.endDateDefault);
      const diffTime = Math.abs(endDate - startDate);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      let minDate;

      if (diffDays > 30) {
        minDate = new Date(startDate);
        minDate.setDate(minDate.getDate() + 30);
      } else {
        minDate = startDate;
      }

      if (student.lastLeaveDate) {
        const lastLeaveDate = new Date(student.lastLeaveDate);
        if (lastLeaveDate > minDate) {
          minDate = lastLeaveDate;
        }
      }
      return {
        disabledDate: (time) => {
          return (
            time.getTime() < minDate.getTime() ||
            time.getTime() > endDate.getTime()
          );
        },
      };
    },
  },
  methods: {
    clickAll(index, value) {
      this.canselAllcheck();

      this.tagIndex = index;
      this.queryParams.cultureStatus = value;
      this.getList();
    },
    initData() {
      this.getCount();
      this.getList();
    },
    async getbatch() {
      await setupBatchData(this);
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    getCount() {
      queryByCountRegisterBase(this.queryParams).then((response) => {
        if (response.data) {
          this.registerBaseVo = response.data;
          this.registerBaseVo.total =
            this.registerBaseVo.cultureStatus1 +
            this.registerBaseVo.cultureStatus2 +
            this.registerBaseVo.cultureStatus3 +
            this.registerBaseVo.cultureStatus4;
        }
      });
    },
    getList() {
      this.loading = true;
      if (this.showType == 1) {
        queryByDeptRegisterBase(this.queryParams).then((response) => {
          this.dataList = response.rows;
          for (let i = 0; i < this.dataList.length; i++) {
            this.dataList[i].total =
              this.dataList[i].cultureStatus1 +
              this.dataList[i].cultureStatus2 +
              this.dataList[i].cultureStatus3 +
              this.dataList[i].cultureStatus4;
          }
          this.total = response.total;
          this.loading = false;
        });
      } else if (this.showType == 2) {
        listRegisterInfo(this.queryParams).then((response) => {
          this.dataList = response.rows;
          this.dataList.forEach((row) => {
            this.$set(row, "check", false);
          });
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    // 变更进修
    modifyOpen() {
      this.modifyForm = {
        registerIdList: this.ids,
        graduationStatus: 1,
        endDate: null,
        engageRemark: null,
      };
      this.modifyShow = true;
    },
    modifySubmit() {
      this.$refs["modifyForm"].validate((valid) => {
        if (valid) {
          // 仅当操作为“提前结业”时，执行特殊校验
          if (this.modifyForm.graduationStatus == 2) {
            // 5. 一次只能选一个人
            if (this.ids.length !== 1) {
              this.$modal.msgError(
                "每次仅支持选择 1 名学员申请提前结业，请重新选择。"
              );
              return;
            }
            const student = this.dataList.find(
              (item) => item.id === this.ids[0]
            );
            if (!student) {
              this.$modal.msgError("未找到选中学员信息。");
              return;
            }
            console.log(student);
            // 1. 已结业的用户不支持申请提前结业
            if (student.graduationStatus == 1) {
              this.$modal.msgError("该学员进修已结束，不支持本操作。");
              return;
            }
            if (!student.registerNoticeVo) {
              this.$modal.msgError("学员信息不完整，无法操作。");
              return;
            }
            const startDate = new Date(student.registerNoticeVo.startDate);
            const originalEndDate = new Date(
              student.registerNoticeVo.endDateDefault
            );
            const newEndDate = new Date(this.modifyForm.endDate);
            // 4. 提前结业时间，不可以小于最晚请假时间
            if (
              student.lastLeaveDate &&
              newEndDate < new Date(student.lastLeaveDate)
            ) {
              this.$modal.msgError("结业时间与请假时间有冲突，请重新设置。");
              return;
            }
            const diffTime = Math.abs(originalEndDate - startDate);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            // 2. 30天也就是一个月的提前结业
            if (diffDays <= 30) {
              if (newEndDate < startDate || newEndDate > originalEndDate) {
                this.$modal.msgError(
                  "申请的提前结业时间需在进修时间范围内，否则无法操作。"
                );
                return;
              }
            } else {
              // 3. 超过30天的
              let minEndDate = new Date(startDate);
              minEndDate.setDate(minEndDate.getDate() + 30);
              if (newEndDate < minEndDate || newEndDate > originalEndDate) {
                this.$modal.msgError(
                  "申请的提前结业时间需在‘进修开始时间 + 30 天’至‘进修结束时间’范围内，否则无法操作。"
                );
                return;
              }
            }
          }
          saveModifyRegisterBase(this.modifyForm).then((response) => {
            this.$modal.msgSuccess("变更成功");
            this.initData();
            this.modifyShow = false;
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    // 设置考评时间
    evaluateOpen() {
      getSureInfo(1).then((response) => {
        this.evaluateForm = response.data;
        if (this.evaluateForm.examineType == 1) {
          this.evaluateForm.examineEndDay = null;
        }
        this.evaluateShow = true;
      });
    },
    evaluateSubmit() {
      this.$refs["evaluateForm"].validate((valid) => {
        if (this.evaluateForm.examineType == 2) {
          if (
            !this.evaluateForm.examineEndDay ||
            this.evaluateForm.examineEndDay <= 0
          ) {
            this.$modal.msgError("请输入带教结束前多少天");
            return;
          }
        }
        if (valid) {
          updateSureInfo(this.evaluateForm).then((response) => {
            this.$modal.msgSuccess("设置成功");
            this.initData();
            this.evaluateShow = false;
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    // 导入考评分数
    scoreOpen() {
      this.upload.url = this.baseURL + "/business/registerBase/scoreImport";
      this.scoreShow = true;
    },
    scoreExport() {
      this.download(
        "business/registerBase/scoreExport",
        {
          ...this.queryParams,
        },
        `培养考核-考评分数打分-${new Date().getTime()}.xlsx`
      );
    },
    // 导入考评等级
    levelOpen() {
      this.upload.url = this.baseURL + "/business/registerBase/levelImport";
      this.levelShow = true;
    },
    levelExport() {
      this.download(
        "business/registerBase/levelExport",
        {
          ...this.queryParams,
        },
        `培养考核-考评等级打分-${new Date().getTime()}.xlsx`
      );
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.scoreShow = false;
      this.levelShow = false;
      this.initData();
    },
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 导出学员手册
    manualOpen() {
      window.location.href =
        this.baseURL +
        "/business/registerBase/exportManual?ids=" +
        this.ids.join(",");
    },
    // 考评评分
    scoreRowOpen(row) {
      for (let i = 0; i < row.registerAllocationVoList.length; i++) {
        let item = row.registerAllocationVoList[i];
        if (item.teacherUserId == this.$store.getters.userId) {
          this.scoreRowForm = item;
          this.scoreRowShow = true;
          return;
        }
      }
      this.$modal.msgError("您不是该学员的带教老师");
    },
    scoreRowSubmit() {
      this.scoreRowForm.scoreTotal =
        (this.scoreRowForm.scoreProfessional || 0) +
        (this.scoreRowForm.scoreLabour || 0) +
        (this.scoreRowForm.scoreDuty || 0) +
        (this.scoreRowForm.scoreOperate || 0) +
        (this.scoreRowForm.scoreMedicalHistory || 0);
      this.$refs["scoreRowForm"].validate((valid) => {
        if (valid) {
          saveScoreRowRegisterBase(this.scoreRowForm).then((response) => {
            this.$modal.msgSuccess("评分成功");
            this.initData();
            this.scoreRowShow = false;
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    // 考评评级
    levelRowOpen(row) {
      if (
        (row.teacherUserId || "").split(",").length !=
        row.registerAllocationVoList.length
      ) {
        this.$modal.msgError("请等待带教老师评分后再进行评级");
        return;
      }
      if (!this.isSecretary) {
        this.$modal.msgError("你不是带教秘书，无法进行评级");
        return;
      }
      this.levelRowForm = {
        id: row.id,
        scoreLevel: row.scoreLevel,
        scoreLevelUserId: this.$store.getters.userId,
      };
      this.levelRowShow = true;
    },
    levelRowSubmit() {
      this.$refs["levelRowForm"].validate((valid) => {
        if (valid) {
          updateRegisterInfo(this.levelRowForm).then((response) => {
            this.$modal.msgSuccess("评级成功");
            this.initData();
            this.levelRowShow = false;
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    // 预览记录手册
    previewOpen(row) {
      console.log(row);
      window.open(
        this.baseURL + "/business/registerBase/exportManualPdf?id=" + row.id
      );
    },
    // 个人信息
    detailOpenInfo(row) {
      this.registerInfo.id = row.id;

      this.detailShowInfo = true;
    },
    // 记录手册
    detailOpen(row) {
      this.registerId = row.id;
      this.detailShow = true;
    },
    /**
     * 处理导出命令。
     *
     * @param {string} command - 导出命令类型，"exportStudent" 或 "exportStudentSummary"
     * @return {void}
     */
    handleExportCommand(command) {
      if (command == "exportStudent") {
        this.exportStudent();
      } else if (command == "exportStudentSummary") {
        this.exportStudentSummary();
      }
    },
    exportStudent() {
      this.download(
        "business/registerBase/exportRegisterInfo",
        {
          ...this.queryParams,
        },
        `导出学员-${new Date().getTime()}.xlsx`
      );
    },
    exportStudentSummary() {
      this.download(
        "business/registerBase/exportRegisterInfoAll",
        {
          ...this.queryParams,
        },
        `导出学员汇总-${new Date().getTime()}.xlsx`
      );
    },
    // 查看名单
    viewOpen(row) {
      this.showType = 2;
      this.queryParams.registerDeptId = row.registerDeptId;
      this.handleQuery();
    },
    // 删除
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除报名信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRegisterInfo(ids);
        })
        .then(() => {
          this.initData();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 切换视图
    showTypeChange() {
      this.canselAllcheck();

      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.queryParams.registerDeptId = null;
      this.queryParams.userName = null;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.canselAllcheck();

      this.queryParams.pageNum = 1;
      this.initData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.canselAllcheck();
      this.resetForm("queryForm");
      // 手动重置批次和年份为空
      this.queryParams.batchName = null;
      this.queryParams.registerYear = null;
      this.handleQuery();
    },
    //取消全选
    canselAllcheck() {
      this.dataList.forEach((item) => {
        if (item.check) {
          this.$set(item, "check", false);
        }
      });
      this.AllCheck = false;
      this.ids = [];
      this.single = true;
      this.multiple = true;
    },
    // 全选
    handleSelectionChangeAll(checked) {
      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        // 使用 $set 确保属性被响应式地修改
        this.$set(this.dataList, i, { ...this.dataList[i], check: checked });
        if (checked) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
      console.log(this.multiple);
      console.log(this.single);
    },
    handleSelectionChange(checked, index) {
      console.log(checked, index);
      // 使用 $set 确保属性被响应式地修改
      this.$set(this.dataList, index, {
        ...this.dataList[index],
        check: checked,
      });

      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].check) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0 20px 20px 20px;
}

::v-deep .el-radio-button__orig-radio + .el-radio-button__inner {
  width: 140px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 140px;
}

.evaluate {
  ::v-deep .el-radio-group {
    display: block;
  }

  ::v-deep .el-radio {
    display: block;
    margin-bottom: 15px;
  }
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  /* 控制列之间的间距 */
  background: #eeeff4;
  padding: 20px 0;
}

.box-container {
  padding: 0;
  padding-left: 20px;
}

.user-name {
  display: flex;
  align-items: center;
}

.custom-table {
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #d8d8d8;
    padding: 0 20px;
    height: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    .col {
      width: calc(100% / 4);
      // font-weight: bolder;

      .desc {
        font-size: 12px;
        color: #888;
        margin-top: 10px;
        font-weight: normal;
      }
    }
  }

  .custom-dept:hover {
    border: 1px solid red;
  }

  .custom-register {
    display: flex;
    justify-content: space-between;
    align-items: center;
    // border: 1px solid rgb(232, 232, 232);
    // padding: 10px;
    // text-align: center;
    font-size: 14px;
    margin-bottom: 10px;
    height: 150px;

    .info {
      display: flex;
      justify-content: space-between;
      color: #606266;
      font-size: 14px;

      .flexInfo {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        font-size: 14px;

        width: 400px;
        line-height: 20px;
        flex: 1;
      }
    }

    .col {
      .desc {
        color: #666666;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    .col:nth-child(1) {
      width: calc(100% - 500px);
      text-align: left;
    }

    .col:nth-child(2) {
      width: 200px;
    }

    .col:nth-child(3) {
      width: 200px;
    }

    .col:nth-child(4) {
      width: 200px;
    }

    .col:nth-child(5) {
      width: 200px;
    }
  }
}

.score-row {
  .section {
    font-size: 18px;
    font-weight: bolder;
    line-height: 50px;
    border-bottom: 2px dashed #f2f3f5;
  }

  ::v-deep .el-form-item {
    margin-bottom: 0;
  }

  .score-row-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 2px dashed #f2f3f5;
    padding: 10px 0;

    .left {
      .title {
        text-align: left;
        font-size: 18px;
        margin-bottom: 15px;
      }
    }

    .right {
      ::v-deep .el-input__inner {
        text-align: center;
        font-size: 18px;
        font-weight: bolder;
      }
    }
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh;
  overflow-y: auto;
}
</style>
